/*
 * create:2016年4月4日 下午6:36:10
 * author:wangds  
 */
package com.cxkj.shop.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cxkj.shop.model.user.User;
import com.cxkj.shop.utils.BusinessUtils;
import com.cxkj.shop.utils.UserUtils;
import com.cxkj.shop.utils.WeiXinHttpsUtils;
import com.cxkj.shop.utils.WxUtils;

import net.wangds.common.GeneralParentObject;
//import net.wangds.common.context.BeanContext;
//import net.wangds.common.context.BeanContextFactory;
import net.wangds.comp.json.JsonUtil;

//import static net.wangds.precasting.context.Constants.SCHEMA_SPRING_PROVIDER;
import net.wangds.utilities.lang.StringUtils;

/**
 * .
 * 
 * @author wangds
 *
 */
public class FillUserServlet extends HttpServlet {

  public static class CONSTANTS {

    public static final String KEY_PARA_CODE = "code";
    public static final String KEY_PARA_STATUS = "status";
    public static final String KEY_CTX_AUTHORIZED_SUB_URI = "CTX_AUTHORIZED_SUB_URI";
    public static final String KEY_CTX_UNAUTHORIZED_SUB_URI = "CTX_UNAUTHORIZED_SUB_URI";
    public static final String BASE_URL_CODE_2_WEB_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token";
    public static final String KEY_WEIXIN_APPID = "appid";
    public static final String KEY_WEIXIN_SECRIT = "secret";
    public static final String KEY_WEIXIN_CODE = "code";
    public static final String KEY_WEIXIN_GRANT_TYPE = "grant_type";
    public static final String KEY_WEIXIN_OPEN_ID = "openid";
    public static final String VALUE_WEIXIN_GRANT_TYPE = "authorization_code";
    public static final String KEY_SESSION_TOKEN_MAP = "KEY_SESSION_TOKEN_MAP";
    public static final String KEY_SESSION_USERINFO_MAP = "KEY_SESSION_USERINFO_MAP";

  }

  /**
   * FillUserServlet.java.
   * 
   * @author wangds 2016年4月4日 下午6:36:51.
   */
  private static final long serialVersionUID = 2780134298761213331L;

  /*
   * @see
   * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
   * javax.servlet.http.HttpServletResponse)
   * 
   * @author wangds 2016年4月4日 下午6:37:01.
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // BeanContext ctx =
    // BeanContextFactory.getBeanContext(SCHEMA_SPRING_PROVIDER);

    String code = req.getParameter(CONSTANTS.KEY_PARA_CODE);

    boolean authorized = StringUtils.isNotBlank(code);
    boolean get_user = false;

    if (authorized) {
      HttpSession session = req.getSession(true);
      get_user = saveUser2Session(session, code);
      if(get_user){
        String open_id = BusinessUtils.getOpenIdSession(session);
        User user = UserUtils.selectUserByOpenId(open_id);
        if(user==null){
          UserUtils.createAndSaveNewUserByOpenId(open_id);
        }
        
      }
    }

    String sub_uri = null;
    if (get_user) {
      sub_uri = "/index.html";// ctx.getBean(CONSTANTS.KEY_CTX_AUTHORIZED_SUB_URI);
    } else {
      sub_uri = "/welcome.html";// ctx.getBean(CONSTANTS.KEY_CTX_UNAUTHORIZED_SUB_URI);
    }

    StringBuilder sb = new StringBuilder();
    sb.append(req.getContextPath());
    sb.append(sub_uri);
    resp.sendRedirect(sb.toString());
  }

  /**
   * .
   * 
   * @author wangds 2016年4月4日 下午8:25:14.
   * @param session
   * @param code
   */
  private boolean saveUser2Session(HttpSession session, String code) {
    boolean res = false;
    try {
      String str_token_resp = WeiXinHttpsUtils
          .httpsGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WxUtils.appId()+"&secret="+WxUtils.appSecret()+"&code=" + code
              + "&grant_type=authorization_code");
      // .out.println(str_token_resp);
      
      GeneralParentObject.staticLogger(this.getClass()).info("access_token_res:"+str_token_resp);
      
      Map<String, Object> map_token_resp = JsonUtil.toHashMap(str_token_resp);
      /*
       * {"access_token":
       * "OezXcEiiBSKSxW0eoylIeKZu8c1uUBN9LHbv8ws8x_LxfNK4v8bB2D8pyguIq7Ke2MNbgVgc2vygfkahV__U6jxpImZMRLmd8JOvtCZuoTvfz9GtLAB7_etLcScpd5ySAwIu2tPDq3po2rplJQ7w4Q",
       * "expires_in":7200, "refresh_token":
       * "OezXcEiiBSKSxW0eoylIeKZu8c1uUBN9LHbv8ws8x_LxfNK4v8bB2D8pyguIq7KemtoP5pbntin0ZmPCNKFqmk7Ey10PJOhwVRXrgEJZUbtUGnfdekNBD8XuobUzT4oWeA_HMQvW0GNMSPHmgu_0lw",
       * "openid":"oP_f5viGo2PKyekcbA5UszaTXZ-Q", "scope":"snsapi_userinfo"}
       */
      session.setAttribute(CONSTANTS.KEY_SESSION_TOKEN_MAP, map_token_resp);
      String str_userinfo_resp = WeiXinHttpsUtils.httpsGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + map_token_resp.get("access_token")
          + "&openid=" + map_token_resp.get("openid") + "&lang=zh_CN");
      // System.out.println(str_userinfo_resp);
      /*
       * {"openid":"oP_f5viGo2PKyekcbA5UszaTXZ-Q", "nickname":"??","sex":1,
       * "language":"zh_CN","city":"??", "province":"??","country":"??",
       * "headimgurl":
       * "http:\/\/wx.qlogo.cn\/mmopen\/LTpwfH82riclpiaibbYRBv3lVGicHZgq0bpHicMGS2o3GsEXoFDib5rYylXfXRzYmZ9ibQperVqjCibVPRCKNrQyU5bW6x2JPtFGCeo3\/0",
       * "privilege":[]}
       */
      Map<String, Object> map_usrinf_resp = JsonUtil.toHashMap(str_userinfo_resp);
      session.setAttribute(CONSTANTS.KEY_SESSION_USERINFO_MAP, map_usrinf_resp);
      res = true;
    } catch (Exception e) {
      GeneralParentObject.staticLogger(this.getClass()).error(e.getLocalizedMessage(), e);
    }
    return res;
  }

}
